#include <stdio.h>
#include <stdlib.h>

int htoi(char *s); // convert a hex string to int(decimal)
int hctoi(char c);

int main(int argc, char *argv[])
{
  int n = htoi("0xff");
  printf("%d\n", n);

  return EXIT_SUCCESS;
}

int htoi(char *s)
{
  int n = 0;
  int hc; // store every single char for hex string

  // handle first two characters
  if (s[0] != '0') { // check if first char is '0', if it does then n remain unchanged
    if ((hc = hctoi(s[0])) >= 0) {
      n = 16 * n + hc;
    }else {
      return n;
    }
  }
  if (s[1] != 'x' && s[1] != 'X') {
    if ((hc = hctoi(s[1])) >= 0) {
      n = 16 * n + hc;
    }else {
      return n;
    }
  }

  for (int i = 2; (hc = hctoi(s[i])) >= 0; i++) {
      n = 16 * n + hc;
  }

  return n;
}

int hctoi(char c) {
  if (c >= '0' && c <= '9') {
    return c - '0';
  }else if (c >= 'a' && c <= 'f') {
    return c - 'a' + 10;
  }else if (c >= 'A' && c <= 'F') {
    return c - 'A' + 10;
  }else {
    return -1; // this char is not a hex number
  }
}
